package com.cn.xt.utils;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;

/**
 * 微信工具类
 * @author liuyu on 2021/1/18.
 */
public class WeiXinUtil {
    public static JSONObject getPhoneNumber(String encryptedData,
                                        String session_key, String iv) {
        // 被加密的数据
        byte[] dataByte = Base64.decodeBase64(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decodeBase64(session_key);
        // 偏移量
        byte[] ivByte = Base64.decodeBase64(iv);
        try {
            // 如果密钥不足16位，那么就补足. 这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base
                        + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters
                    .getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                return JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static void main(String[] args) {
        // String urlString = "https://api.weixin.qq.com/sns/jscode2session";
        // String APP_ID = Constants.WX_APPID;
        // String APP_SECRET = Constants.WX_APPSCRECRET;
        // String code = "091t5FFa1x7ADA0vAQHa1RT3j20t5FF6";
        // String param = "appid=" + APP_ID + "&secret=" + APP_SECRET
        // + "&js_code=" + code + "&grant_type=authorization_code";
        // String result = Utils.sendGet(urlString, param);
        // System.out.println("result:" + result);

        // 第三步骤：注释上一步，将sessionKey替换下面的测试纸，将获取手机号
        // 三种获取手机号的方式都可以
        String encryptedData = "QL6vRNFsMPF1TukxYn9UDu6Y5F32hF7e1WdZ72uvSEPLP4qKyzdO0dDRfPVPpB+Zhd6Dbv/rCMt60uFFScFDtdYyyS8zK/t6t7PE5Orbc9Mx5QFDyMQNnGMXkNscf9yUuekn/+XsarCxOUyUzUj7WKpYukU6OcB5wrIjRgexfXfy/1SgfmLbIYRc0WkUbnTnS40SDyXKTVmBGLlDM0Q4qA==";
        String sessionKey = "0RBldt5CWG9pE+NeUEigsA==";
        String iv = "MFXGfVJJcY+f7TSiOjO7sw==";

        Object object = getPhoneNumber(encryptedData, sessionKey, iv);
        System.out.println("object:" + object);

        Object object2 = getPhoneNumber(encryptedData, sessionKey, iv);
        System.out.println("object2:" + object2);
    }
}
